﻿using Advertising.Client.UI.CategorySer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace Advertising.Client.UI.Controllers
{
    public class AdminApiController : ApiController
    {
        private readonly CategoryServiceClient db = new CategoryServiceClient();

        public HttpResponseMessage PostCategory(Category category)
        {
            if (ModelState.IsValid)
            {
                db.AddNewCategory(category);
                return Request.CreateResponse(HttpStatusCode.Created, category); 
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

        public IEnumerable<Category> GetCategories()
        {
            var tmp = db.ListCategories();
            return tmp;
        }

        public HttpResponseMessage PutCategory(Category category)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (db.EditCategory(category) != 0)
            {
                return Request.CreateResponse(HttpStatusCode.OK, category);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");
            }
        }

        public HttpResponseMessage DeleteCategory(int id)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (db.DeleteCategory(id) != 0)
            {
                return Request.CreateResponse(HttpStatusCode.OK, id);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");
            }
        }

        public Task<IEnumerable<string>> PostCategoryWithIcon()
        {
            if (Request.Content.IsMimeMultipartContent())
            {
                string fullPath = HttpContext.Current.Server.MapPath("~/App_Data/Category");
                MyMultipartFormDataStreamProvider streamProvider = new MyMultipartFormDataStreamProvider(fullPath);
                var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                        throw new HttpResponseException(HttpStatusCode.InternalServerError);

                    var fileInfo = streamProvider.FileData.Select(i =>
                    {
                        var info = new FileInfo(i.LocalFileName);
                        return "File uploaded as " + info.FullName + " (" + info.Length + ")";
                    });
                    return fileInfo;

                });
                return task;
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
            }
        }

        public class MyMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
        {
            public MyMultipartFormDataStreamProvider(string path)
                : base(path)
            {

            }

            public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
            {
                string fileName;
                if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName))
                {
                    fileName = headers.ContentDisposition.FileName;
                }
                else
                {
                    fileName = Guid.NewGuid().ToString() + ".data";
                }
                return fileName.Replace("\"", string.Empty);
            }
        }
    }
}
